
import upng from "../../../utils/UPNG.js"
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度
const platform = wx.getSystemInfoSync().platform;
const version = wx.getSystemInfoSync().version;
// pages/shouxieban/shouxieban.js
Page({
  /**
 * 页面的初始数据
 */
  data: {
    //canvas宽高
    canvasw: 0,
    canvash: 0,
    screenWidth:"",
    leftH:0,
    
    //canvas生成的图片路径
    canvasimgsrc: "",
    base64Src:""
  },
  onLoad: function (options) {
    //画布初始化执行
    var that = this;
    
    var query = wx.createSelectorQuery()
    query.select('#J_hand-left').boundingClientRect()
    query.exec(function (res) {
     
        that.setData({
          leftH:res[0].height
        })
    })
   

    
    setTimeout(function(){
      that.startCanvas();
    },500);

  },
  //画布初始化执行
  startCanvas: function () {
    var that = this;
    //创建canvas
    this.initCanvas();
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        
        
        canvasw = res.screenWidth;//设备宽度
        canvash = res.windowHeight - that.data.leftH;
        that.setData({ 
          'canvasw': canvasw,
          'canvash': canvash,
          'screenWidth': res.screenWidth  
        });
      }
    });
  },
  //初始化函数
  initCanvas: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.rotate(-45)
    context.beginPath()
  
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    
    context.setLineCap('round');
    context.setLineJoin('round');
    
  },
  //事件监听
  canvasIdErrorCallback: function (e) {
    
  },
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);

  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);

    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };
    context.clearRect(0, 0, canvasw, canvash);

    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  //清除画布
  cleardraw: function () {
    //清除画布
    this.setData({
      testSrc:""
    })
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
  //提交签名内容
  setSign: function () {
    var that = this;
    if (arrx.length == 0) {
      wx.showModal({
        title: '提示',
        content: '签名内容不能为空！',
        showCancel: false
      });
      return false;
    };

   

    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function (res) {
        that.setData({ canvasimgsrc: res.tempFilePath });
        wx.canvasGetImageData({
          canvasId: "canvas",
          x: 0,
          y: 0,
          width: that.data.canvasw,
          height: that.data.canvash,
          success(res) {
            if (platform == 'ios' && version <="6.7.2") {
              // 兼容处理：ios获取的图片上下颠倒 
              res =that.reverseImgData(res)
            }
         
            let pngData = upng.encode([res.data.buffer], res.width, res.height)

           
            // 4. base64编码
            let base64 = wx.arrayBufferToBase64(pngData)
            that.cleardraw();
            // that.setData({
            //   testSrc: "data:image/jpeg;base64," + base64
            // })
            wx.navigateTo({
              "url": "/pages/index/signonline/signonline?fromwhere=qianming&imgsrc=" + that.data.canvasimgsrc + "&base64src=" + base64 + "&w=" + res.width+"&h="+res.height
            })

          }
        });
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: '微信当前版本不支持，请更新到最新版本！',
          showCancel: false
        });
      },
      complete: function () {

      }
    })
    
    //生成图片
    

  },
  reverseImgData(res) {
    var w = res.width
    var h = res.height
    let con = 0
    for (var i = 0; i < h / 2; i++) {
      for (var j = 0; j < w * 4; j++) {
        con = res.data[i * w * 4 + j]
        res.data[i * w * 4 + j] = res.data[(h - i - 1) * w * 4 + j]
        res.data[(h - i - 1) * w * 4 + j] = con
      }
    }
    return res
  }
  /**
   * 生命周期函数--监听页面加载
   */
 
})
